<template>
  <el-card class="box-card">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="width: 300px">
      <el-breadcrumb-item style="font-size: 16px">首页</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px">用户管理</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 16px"
        >管理员列表管理</el-breadcrumb-item
      >
    </el-breadcrumb>
    <div class="addUser">
      <!-- 对话框组件  :visible.sync(设置是否显示对话框) width(设置对话框的宽度)
:before-close(在对话框关闭前触发的事件) -->
      <el-dialog
        title="添加管理员"
        :visible.sync="addDialogVisible"
        width="40%"
        @close="addDialogClosed()"
      >
        <!-- 对话框主体区域 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="80px"
          style="padding: 10px 20px"
        >
          <el-form-item label="用户名" prop="name" style="height: 50px">
            <el-input v-model="addForm.name" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" style="height: 50px">
            <el-input v-model="addForm.email" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" style="height: 50px">
            <el-input v-model="addForm.password" style="width: 50%"></el-input>
          </el-form-item>
          <el-form-item label="分配角色" style="height: 50px">
            <el-select
              placeholder="分配角色"
              style="width: 50%"
              v-model="addForm.role"
            >
              <el-option
                v-for="(item, index) in roleList"
                :key="item.roleName"
                :value="item.roleName"
                >{{ item.roleName }}</el-option
              >
            </el-select>
          </el-form-item>
        </el-form>
        <!-- 对话框底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCancel">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <el-button
        v-if="showAdd"
        type="primary"
        @click="showAddDialog()"
        style="
          float: right;
          margin-top: -25px;
          margin-bottm: 20px;
          margin-right: 125px;
        "
        >添加管理员</el-button
      >
    </div>
    <el-table
      :data="userData"
      border
      style="width: 961px; margin-left: 40px"
      :header-cell-style="headClass"
    >
      <el-table-column label="序号" width="80" type="index" align="center">
      </el-table-column>
      <el-table-column label="用户名" width="130" prop="name" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="250" prop="email" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="密码" width="150" prop="password">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.password }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="角色" width="250" prop="password" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="showEdit"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="showEditDialog(scope.row.name)"
          ></el-button>
          <el-button
            v-if="showRemove"
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeUserById(scope.row.name)"
          ></el-button>
          <!-- <el-button
            size="mini"
            type="warning"
            icon="el-icon-star-off"
            @click="assignPrmissions(scope.row.name)"
            >分配角色</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="修改信息"
      :visible.sync="editDialogVisible"
      width="40%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="80px"
        style="padding: 10px 20px"
      >
        <el-form-item label="用户名" prop="name" style="height: 50px">
          <el-input
            v-model="editForm.name"
            autocomplete="off"
            style="width: 50%"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" style="height: 50px">
          <el-input
            v-model="editForm.email"
            autocomplete="off"
            style="width: 50%"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" style="height: 50px">
          <el-input
            v-model="editForm.password"
            autocomplete="off"
            style="width: 50%"
          ></el-input>
        </el-form-item>
        <el-form-item label="分配角色" style="height: 50px">
          <el-select
            placeholder="分配角色"
            style="width: 50%"
            v-model="editForm.role"
          >
            <el-option
              v-for="(item, index) in roleList"
              :key="item.roleName"
              :value="item.roleName"
              >{{ item.roleName }}</el-option
            >
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      class="pagination"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-size="queryInfo.pagesize"
      layout="total, prev, pager, next"
      :total="queryInfo.count"
      background
    >
      <!--
        @current-change(页码发生改变时触发)
        :current-page(设置当前页码)
        :page-size(设置每页的数据条数)
        :total(设置总页数)
     -->
    </el-pagination>
  </el-card>
</template>

<script>
import qs from "qs";
import Base64 from "base-64";
export default {
  data() {
    var validateName = (rule, value, callback) => {
      let reg = /^[^_]\S{2,16}[^_]$/;
      if (!value) {
        callback(new Error("用户名不可为空!"));
      } else {
        if (!reg.test(value)) {
          callback(
            new Error("用户名不能以下划线开头和结尾，且必须大于2位！！")
          );
        } else {
          callback();
        }
      }
    };
    var validatePass = (rule, value, callback) => {
      let reg = /^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S{6,16}$/;
      if (!value) {
        callback(new Error("用户名不可为空!"));
      } else {
        if (value.length < 6) {
          callback(new Error("密码需大于6位!"));
        }
        if (value.length > 16) {
          callback(new Error("用户名需小于16位!"));
        } else if (!reg.test(value)) {
          callback(
            new Error(
              "密码需包含小写字母、大写字母、数字、特殊符号的两种及以上!"
            )
          );
        } else {
          callback();
        }
      }
    };
    //验证邮箱的规则
    var validataEmail = (rule, value, callback) => {
      const reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (!value) {
        callback(new Error("邮箱不可为空!"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("邮箱输入格式有误!请重新输入！"));
        } else {
          callback();
        }
      }
    };
    return {
      // 按钮显示隐藏
      showAdd: true,
      showEdit: true,
      showRemove: true,
      // 角色列表
      roleList: [],
      // 控制修改院校
      editDialogVisible: false,
      // 添加用户
      addDialogVisible: false,
      addForm: {
        name: "",
        email: "",
        password: "",
        role: "",
      },
      addFormRules: {
        name: [{ required: true, validator: validateName, trigger: "blur" }],
        email: [{ required: true, validator: validataEmail, trigger: "blur" }],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
      },
      // 修改用户的表单数据
      editForm: {
        fname: "",
        name: "",
        email: "",
        password: "",
        role: "",
      },
      // 属性
      editFormRules: {
        name: [{ required: true, validator: validateName, trigger: "blur" }],
        email: [{ required: true, validator: validataEmail, trigger: "blur" }],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        role: [
          {
            required: true,
            message: "请选择将要分配的角色",
            trigger: "change",
          },
        ],
      },
      //初始分页条件
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 9,
        count: 0,
      },
      // 保存请求回来的用户列表数据
      userData: [
        {
          // order: 1,
          name: "wyf",
          email: "1959198478@qq.com",
          password: "123456",
          roleName: "超级管理员",
        },
      ],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      formLabelWidth: "120px",
    };
  },
  methods: {
    headClass() {
      //表头居中显示
      return "color:rgba(255,101,0);font-weight:bold;font-size:16px";
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    handleCurrentChange(page) {
      this.queryInfo.pagenum = page;
      //   this.getLists();
      console.log("跳转了");
      // 重新按照pagenum发送请求 请求最新的数据
      this.getUseriList();
    },
    getUserList_Token() {
      const token = window.sessionStorage.getItem("tokenvalue");
      this.$axios.defaults.headers.common["satoken"] = token;
      this.$axios
        .get("/back/admins", {
          params: {
            page: this.queryInfo.pagenum,
            size: this.queryInfo.pagesize,
          },
        })
        .then((res) => {
          console.log(res);
          this.userData = res.data.data;
          // this.queryInfo.count = res.data.count;
        });
    },
    // 添加
    addDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.addFormRef.resetFields();
    },
    addCancel() {
      this.addDialogVisible = false;
      this.$message("取消添加");
    },
    showAddDialog() {
      //显示弹出窗
      this.addDialogVisible = true;
      this.$axios.get("/back/permission/roles").then((res) => {
        console.log(res);
        this.roleList = res.data;
      });
    },
    addUser() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return;
        else {
          this.$axios
            .post(
              "/back/admin",
              qs.stringify({
                name: this.addForm.name,
                email: this.addForm.email,
                password: Base64.encode(this.addForm.password),
                roleName: this.addForm.role,
              })
            )
            .then((res) => {
              console.log(res);
              this.getUserList_Token();
              this.$message.success("添加用户成功！");
              this.addDialogVisible = false;
            });
        }
      });
    },
    // 修改
    showEditDialog(name) {
      // 获取角色列表
      this.$axios.get("/back/permission/roles").then((res) => {
        console.log(res);
        this.roleList = res.data;
      });
      //将获取到的数据保存到数据editForm中
      this.editForm.fname = name;
      //显示弹出窗
      this.editDialogVisible = true;
      // });
    },
    editDialogClosed() {
      // 对话框关闭之后，重置表单
      this.$refs.editFormRef.resetFields();
    },

    cancel() {
      this.editDialogVisible = false;
      this.$message("取消修改");
    },
    editUser() {
      // // 用户点击修改表单中的确定按钮之后，验证表单数据
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        // 发送请求 完成修改用户的操作
        else {
          this.$axios
            .put(
              "/back/admin",
              qs.stringify({
                fName: this.editForm.fname,
                name: this.editForm.name,
                email: this.editForm.email,
                password: Base64.encode(this.editForm.password),
                roleName: this.editForm.role,
              })
            )
            .then((res) => {
              //修改成功的提示
              this.$message.success("修改用户成功");
              //关闭对话框
              this.editDialogVisible = false;
              //重新请求最新的数据
              this.getUserList_Token();
            });
        }
      });
    },
    removeUserById(name) {
      //弹出确定取消框，是否删除用户
      this.$confirm("请问是否要永久删除该用户", "删除提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确认删除",
        cancelButtonText: "取消",
      })
        .then(() => {
          //发送请求根据id完成删除操作
          this.$axios.delete("/back/admin/" + name).then((res) => {
            this.$message.success("删除用户成功");
            //重新请求最新的数据
            this.getUserList_Token();
          });
        })
        .catch((action) => {
          this.$message({
            type: "info",
            message: action === "cancel" ? "取消删除" : "放弃删除",
          });
        });
    },
  },
  created() {
    this.getUserList_Token();
    this.$axios.get("/back/admin/addButton").then((res) => {
      if (res.data.code === 500) {
        this.showAdd = false;
      }
    });
    this.$axios.get("/back/admin/updateButton").then((res) => {
      if (res.data.code === 500) {
        this.showEdit = false;
      }
    });
    this.$axios.get("/back/admin/deleteButton").then((res) => {
      if (res.data.code === 500) {
        this.showRemove = false;
      }
    });
  },
};
</script>

<style scoped>
.box-card {
  position: relative;
  margin: 22px auto;
  min-height: 550px;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.search {
  margin-top: 20px;
  margin-left: 40px;
  width: 400px;
  /* position: absolute; */
  /* right: 80px;
  top: 6px; */
}

.el-table {
  margin-top: 20px;
}

/* .el-dialog .el-dialog__body {
  padding: 10px 20px;
} */

.el-dialog .el-dialog__body {
  padding: 10px 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.pagination {
  /* border: 1px solid red; */
  position: absolute;
  bottom: 20px;
  width: 412px;
  margin: 5px auto;
  /* height: 30px; */
  left: 50%;
  margin-left: -206px;
}
</style>